package cadc.daos;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import cadc.models.FileItem;

public class FileItemDao extends JdbcDaoSupport {

	public FileItem getFileItemById(int id) {
		String sql = "select * from files where id="+id;
		List<FileItem> items = super.getJdbcTemplate().query(sql, new FileItemRowMapper());
		if(items.isEmpty()||items.size()==0)return null;
		else return items.get(0);
	}
	
	public void changeName(String newName, long id){
		String sql = "update files set name=? where id="+id;
		super.getJdbcTemplate().update(sql, newName);
	}

	class FileItemRowMapper implements RowMapper<FileItem>{
		@Override
		public FileItem mapRow(ResultSet rs, int rowNum) throws SQLException {
			FileItem item = new FileItem();
			item.setId(rs.getInt("id"));
			item.setItemContentType(rs.getString("contentType"));
			item.setItemFileName(rs.getString("name"));
			item.setKey(rs.getString("passkey"));
			item.setSize(rs.getInt("size"));
			return item;
		}	
	}

	public int saveFileItem(FileItem fi) {
		String sql = "insert into files (id, name, contentType, size, passkey) values (null, ?, ?, ?, ?)";
		if(super.getJdbcTemplate().update(sql, fi.getItemFileName(), fi.getItemContentType(), fi.getSize(), fi.getKey())>0){
			return super.getJdbcTemplate().queryForInt("select max(id) from files");
		}else return 0;
	}
	
}
